// pages/shopManager/customizeImg/customizeImg.js
const common = require('../../utils/util.js')
const md5 = require('../../utils/md5.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        nowDate: '',
        shopInfo: null,
        ewmCode: null,
        customizeImg: null,
        uploadImg: '',
        showCropper: false,
        width: 250, //宽度
        height: 310, //高度
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        // this.getShopInfo()
        this.setData({
            nowDate: new Date().getTime()
        })
        this.getEwmCode()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    back() {
        this.setData({
            uploadImg: '',
            showCropper: false
        })
    },

    clickcut(e) {
        this.setData({
            uploadImg: e.detail.url
        })
        this.createImg()
    },

    loadimage(e) {
        //重置图片角度、缩放、位置
        this.cropper.imgReset();
    },

    getShopInfo: function() {
        const that = this
        let data = {
            store_id: wx.getStorageSync('realStoreId')
        }
        common.post('Store/get_store_info', data).then(function(res) {
            wx.hideLoading()
            if (res.code == 204) {
                return
            } else {
                that.setData({
                    shopInfo: res
                })
            }
        }).catch(function(e) {})
    },

    getEwmCode: function() {
        const that = this
        let data = {}
        common.post('QrCodes/app_create_qr', data).then(function(res) {
            that.setData({
                ewmCode: res
            })
        }).catch(function(e) {})
    },

    upLoadImg: function() {
        const that = this
        let data = {}
        let key = wx.getStorageSync('token')
        let sign = 'mdl'
        let timestamp = Date.parse(new Date())
        data.key = key
        data.timestamp = timestamp
        data = this.objKeySort(data)
        for (let i in data) {
            sign += (i + data[i])
        }
        sign += 'mdl'
        sign = md5(sign)
        data.sign = sign
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function(res) {
                let tempFilePaths = res.tempFilePaths
                let tempUrl = 'https://www.meiboshi.vip/api/Upimg/up_comment_img'
                let tempData = {
                    key: data.key,
                    timestamp: data.timestamp,
                    sign: data.sign
                }
                common.uploadImage(tempFilePaths, tempUrl, tempData).then(function(res) {
                    that.setData({
                        uploadImg: res[0],
                        showCropper: true
                    })
                    //获取到image-cropper对象
                    that.cropper = that.selectComponent("#image-cropper");
                    // that.createImg()
                })
            }
        })
    },

    createImg: function() {
        wx.showLoading({
            title: '生成图片中'
        })
        const that = this
        const wxGetImageInfo = this.promisify(wx.getImageInfo)
        Promise.all([
            wxGetImageInfo({
                src: that.data.uploadImg
            }),
            wxGetImageInfo({
                src: that.data.ewmCode
            }),
            wxGetImageInfo({
                src: 'https://www.meiboshi.vip/static/images/wx_sm/home/customize-img-logo.png'
            })
        ]).then(res => {
            const ctx = wx.createCanvasContext('createCanvas')
            ctx.rect(0, 0, 750, 1334)
            ctx.setFillStyle('white')
            ctx.fill()
            ctx.drawImage(res[0].path, 0, 0, 750, 930)
            ctx.drawImage(res[1].path, 450, 960, 250, 250)
            ctx.drawImage(res[2].path, 80, 980, 283, 204)
            // ctx.font = 'bold'
            // ctx.setFillStyle('#131313')
            // ctx.setFontSize(46)
            // if (that.data.shopInfo.store_name.length > 6) {
            //     ctx.fillText(that.data.shopInfo.store_name.slice(0, 6) + '...', 48, 1060)
            // } else {
            //     ctx.fillText(that.data.shopInfo.store_name, 48, 1060)
            // }
            // ctx.setFillStyle('#323232')
            // ctx.setFontSize(30)
            // ctx.fillText('成为本店专属VIP', 48, 1130)
            // ctx.fillText('享受全年0利白领', 48, 1180)
            ctx.draw(false, function(e) {
                wx.hideLoading()
                const wxCanvasToTempFilePath = that.promisify(wx.canvasToTempFilePath)
                wxCanvasToTempFilePath({
                    canvasId: 'createCanvas',
                    x: 0,
                    y: 0,
                    width: 750,
                    height: 1234
                }, this).then(res => {
                    wx.hideLoading()
                    that.setData({
                        customizeImg: res.tempFilePath,
                        uploadImg: '',
                        showCropper: false
                    })
                })
            })
        })
    },

    objKeySort: function(obj) {
        let newkey = Object.keys(obj).sort()
        let newObj = {}
        for (let i = 0; i < newkey.length; i++) {
            newObj[newkey[i]] = obj[newkey[i]]
        }
        return newObj
    },

    promisify: function(api) {
        return (options, ...params) => {
            return new Promise((resolve, reject) => {
                const extras = {
                    success: resolve,
                    fail: reject
                }
                api({
                    ...options,
                    ...extras
                }, ...params)
            })
        }
    },

    circleImg: function(ctx, img, x, y, r) {
        ctx.save();
        var d = 2 * r;
        var cx = x + r;
        var cy = y + r;
        ctx.arc(cx, cy, r, 0, 2 * Math.PI);
        ctx.clip();
        ctx.drawImage(img, x, y, d, d);
        ctx.restore();
    },

    goSave: function() {
        if (this.data.customizeImg == null) {
            wx.showToast({
                title: '请上传自定义海报图',
                icon: 'none',
                duration: 2000
            })
            return
        }
        const that = this
        wx.saveImageToPhotosAlbum({
            filePath: this.data.customizeImg,
            success: function(data) {
                wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                })
            },
            fail: function(err) {
                if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                    wx.showModal({
                        title: '用户未授权',
                        content: '请先开启保存到相册权限，开启后即可保存图片',
                        success(res) {
                            if (res.confirm) {
                                wx.openSetting({
                                    success(settingdata) {
                                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                            wx.saveImageToPhotosAlbum({
                                                filePath: that.data.customizeImg,
                                                success(res) {
                                                    wx.showToast({
                                                        title: '保存成功',
                                                        icon: 'success',
                                                        duration: 2000
                                                    })
                                                }
                                            })
                                        } else {
                                            wx.showToast({
                                                title: '保存图片失败，请确认开启授权后重新保存图片',
                                                icon: 'none',
                                                duration: 2000
                                            })
                                        }
                                    }
                                })
                            } else if (res.cancel) {
                                wx.showToast({
                                    title: '保存图片失败，请确认开启授权后重新保存图片',
                                    icon: 'none',
                                    duration: 2000
                                })
                            }
                        }
                    })
                }
            }
        })
    }
})